<?php



namespace app\bbxw\controller\api;



use app\bbxw\service\WechatService;
use app\bbxw\service\UserAdminService;
use think\admin\Controller;
use app\bbxw\model\WxUser as WxUserMod;
use think\admin\model\SystemUser;

/**
 * 微信用户登录接口
 * Class Login
 * @package app\data\controller\api
 */
class WxLogin extends Controller
{
    /**
     * 接口认证类型
     * @var string
     */
    private $type;

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        // 接收接口类型

        $this->type = $this->type ?: $this->request->header('api-name');
        if (empty(UserAdminService::TYPES[$this->type])) {
            $this->error("接口类型[{$this->type}]未定义规则！");
        }
    }

    /**
     * 用户登录接口
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function in()
    {
        $data = $this->request->get();
         $this->_vali([
            'code.require'    => 'code不能为空！',
        ],$data);
        //获取openid
        $oauth_info = WechatService::WeChatOauth()->getOauthAccessToken($data['code'],2);
        if(!isset($oauth_info['openid'])) $this->error("openid 获取失败");
        $data['openid'] = $openid = $oauth_info['openid'];
        $user = $this->app->db->name("wechat_fans")->field("id,openid,nickname,headimgurl")->where(['openid'=>$openid])->find();
        if($user){
            $this->success('登录成功！', UserAdminService::set(['openid'=>$openid], [], $this->type, true));
        }else{
            $this->app->db->name("wechat_fans")->insert(['openid'=>$data['openid']]);
            $this->success('登录成功！', UserAdminService::set(['openid'=>$openid], [], $this->type, true),2);
        }
    }

    public function saveUser(){
        $data = $this->request->post();
        $this->_vali([
            'id.require'    => '主键不能为空！',
            'nickname.require'    => '昵称不能为空！',
            'headimgurl.require'    => '头像不能为空！',
        ],$data);
         $this->app->db->name("wechat_fans")->save($data);
        $user = $this->app->db->name("wechat_fans")->where(['id'=>$data['id']])->find();
        $this->success('保存成功！',$user);
    }







}